package my.suveng.util.dynamic.datatsource.aspect;

import cn.hutool.core.lang.caller.CallerUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import my.suveng.util.dynamic.datatsource.DynamicDataSourceContextHolder;
import my.suveng.util.dynamic.datatsource.annotations.ChooseDatasource;
import my.suveng.util.dynamic.datatsource.annotations.DatasourceRoleType;
import my.suveng.util.dynamic.datatsource.route.DataSourcePolling;
import my.suveng.util.log.PlusLogFactoryHutool;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 切面控制数据源
 * @author suwenguang
 **/
@Aspect
@Component
public class DynamicAspect {

    //hutool日志
    private static final Log log = LogFactory.setCurrentLogFactory(new PlusLogFactoryHutool()).getLog(CallerUtil.getCaller().getName());

    @Pointcut(value = "execution( * *..*.*(..)) ")
    public void dao() {
    }

    /**
     * 切面方法,用于接口切面AOP增强
     * @author suwenguang
     * @date 2019-09-25
     */
    @Around(value = "dao() && @annotation(chooseDatasource)", argNames = "pjp,chooseDatasource")
    public Object aroundMethod(ProceedingJoinPoint pjp, ChooseDatasource chooseDatasource) throws Throwable {
        // 根据注解选择数据源
        DatasourceRoleType type = chooseDatasource.type();
        if (DatasourceRoleType.master.equals(type)) {
            DynamicDataSourceContextHolder.setDataSourceType(DatasourceRoleType.master.getName());
        } else {
            DynamicDataSourceContextHolder.setDataSourceType(DataSourcePolling.autoPolling());
        }
        Object result = pjp.proceed();

        //设置完 手动清空
        DynamicDataSourceContextHolder.clearDataSourceType();
        return result;
    }

}
